#include "ast.h"


void yyerror(char* msg){
	extern int yylineno;
	fprintf(stderr, "Error type B at Line %d: error is near \"%s\".\n", yylineno, yytext);
    my_is_error = 1;
}


char *generate_blank(int level) {
    char *s = (char *) malloc((level * 2 + 1) * sizeof(char));
    for (int i = 0; i < level * 2; i++) {
        s[i] = ' ';
    }
    s[level * 2] = '\0';
    return s;
}

void root_first(TreeNode *root, int level) {
    if (root != NULL) {
        char *blank = generate_blank(level);
		switch (root->type){
			case 0:
				printf("%s%s: %f\n", blank, root->name, root->float_val);
				break;
			case 1:
				printf("%s%s: %d\n", blank, root->name, root->int_val);
				break;
			case 2:
				printf("%s%s: %s\n", blank, root->name, root->type_val);
				break;
			case 3:
				printf("%s%s (%d)\n", blank, root->name, root->line);
				break;
			case 5:
				printf("%s%s\n", blank, root->name);
				break;
			default:
				break;
		}
        for (int i = 0; i < root->children_num; i++) {
			root_first(root->children[i], level + 1);
        }
    }
}

TreeNode* new_node_float(char* name, float float_val){
	TreeNode* temp = (TreeNode*) malloc(sizeof(TreeNode));
	temp->name = name;
	temp->float_val = float_val;
	temp->type = 0;
	return temp;
}
TreeNode* new_node_int(char* name, int int_val){
	TreeNode* temp = (TreeNode*) malloc(sizeof(TreeNode));
	temp->name = name;
	temp->int_val = int_val;
	temp->type = 1;
	return temp;
}
TreeNode* new_node_str(char* name, char* type_val){
	TreeNode* temp = (TreeNode*) malloc(sizeof(TreeNode));
	temp->name = name;
	temp->type_val = type_val;
	temp->type = 2;
	return temp;
}
TreeNode* new_node_syntax(char* name, int line){
	TreeNode* temp = (TreeNode*) malloc(sizeof(TreeNode));
	temp->name = name;
	temp->type = 3;
	temp->line = line;
	return temp;
}
TreeNode* new_node_null(){
	TreeNode* temp = (TreeNode*) malloc(sizeof(TreeNode));
	temp->type = 4;
	return temp;
}
TreeNode* new_node_terminal(char* name){
	TreeNode* temp = (TreeNode*) malloc(sizeof(TreeNode));
	temp->name = name;
	temp->type = 5;
	return temp;
}
TreeNode* new_node(TreeNode* parent, TreeNode* children[MAX_CHILDREN], int num){
	for(int i=0; i<num; i++){
		parent->children[i] = children[i];
	}
	parent->children_num = num;
}



int main(int argc,char ** argv){
	if (argc <= 1) return 1;
	FILE* f = fopen(argv[1],"r");
	if(!f)
	{
		perror(argv[1]);
		return 1;
	}
	yyrestart(f);
	//yydebug = 1;
	yyparse();

	/*
	TreeNode* a = new_node_float("aaa", 0.01);
	printf("%d,%f", a->int_val,a->float_val);
	*/

	if (my_is_error == 0) {
        root_first(root, 0);
    }
	return 0;
}

